package com.lizhongbao.cloud.feign.web;

import com.lizhongbao.cloud.feign.client.GatewayHelloClient;
import com.lizhongbao.cloud.feign.client.HelloClient;
import com.lizhongbao.cloud.feign.extension.RequestContext;
import com.lizhongbao.cloud.feign.service.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.*;

@RestController
public class HelloController {

    @Autowired
    private HelloClient helloClient;

    @Autowired
    private GatewayHelloClient gatewayHelloClient;

    @Autowired
    private TestServiceImpl testService;

    @GetMapping("hello")
    public String sayHello(){
        String str = "8083端口正在被调用:" + RequestContext.getXUser() + ",";
        testService.hello();
        sayHelloExecutor();
        return str + helloClient.hello();
    }

    @GetMapping("/gateway/hello")
    public String gatewayHello(){
        String str = "通过Gateway网关调用:";
        return str + gatewayHelloClient.hello();
    }

    /**
     * 大于核心线程数的线程空闲多久后被移除
     */
    public static final long KEEP_ALIVE_TIME = 0L;
    /**
     * 核心线程数
     */
    public static final int CORE_POOL_SIZE = 10;
    /**
     * 最大线程数
     */
    public static final int MAXIMUM_POOL_SIZE = 10;

    /**
     * @Description 发送短信
     * @Author lizhongbao
     * @Date 2019/10/26
     * @Params [market, memberList]
     * @Return void
     */
    public void sayHelloExecutor() {
        // 创建线程池
        ExecutorService executorService = this.getExecutorService(2);
        executorService.submit(() -> testService.hello());
        executorService.submit(() -> testService.hello());
        executorService.shutdown();
    }

    /**
     * @Description 获取线程池
     * @Author lizhongbao
     * @Date 2019/11/1
     * @Params [size]
     * @Return java.util.concurrent.ExecutorService
     */
    public ExecutorService getExecutorService(int size) {
        ExecutorService executorService = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(size),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        return executorService;
    }
}